package org.stvd.controller.user;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.common.utils.ServiceResult;
import org.stvd.common.utils.encode.Base64Util;
import org.stvd.common.utils.encode.RSAUtil;
import org.stvd.controller.BaseController;
import org.stvd.service.admin.UsersService;

/**
 * 重置密码-控制类
 * @author hzx
 */
@Controller
public class ResetPwdController extends BaseController{

    @Autowired
    private UsersService usersService;//账户信息Service
    
    private static final Logger logger = Logger.getLogger(RegistController.class);
    
    private String ftlURL = "/user/";//路径模板
    
    /**
     * 手机号重置密码
     * @param users
     * @return
     */
    @GetMapping(value = "mobile_reset")
    public String onResetForMobileLoad(HttpServletRequest request,ModelMap map) {
        //获取公钥信息
        String path = this.getClass().getResource("/rsakey/publicKey.txt").getFile();
        String publicKey = RSAUtil.readTxt(path);
        map.put("publicKey", publicKey);
        return ftlURL + "ResetPwdForMobile.html";
    }
    
    @Log(title = "使用手机号重置密码", businessType = BusinessType.OTHER)
    @PostMapping(value = "mobile_reset")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> UserPasswordResetForMobileAction() {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<>();
        String mobileStr = request.getParameter("mobilenum");
        String validateCode = request.getParameter("validatecode");
        String newPassword = request.getParameter("newpass");
        String confirmPassword = request.getParameter("confirmpass");
        try {
            // RSA解密
            String privateKey = RSAUtil.readTxt(this.getClass().getResource("/rsakey/privateKey.txt").getFile());
            newPassword = newPassword.replaceAll("%2B","+");
            byte[] decryptPassWord = RSAUtil.decryptByPrivateKey(Base64Util.decode(newPassword), privateKey);
            newPassword = new String(decryptPassWord);
            confirmPassword = confirmPassword.replaceAll("%2B","+");
            byte[] decryptComfirmPass = RSAUtil.decryptByPrivateKey(Base64Util.decode(confirmPassword), privateKey);
            confirmPassword = new String(decryptComfirmPass);
            result.transferResult(usersService.resetpwdForUserMobile(mobileStr, validateCode, newPassword, confirmPassword));
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("数据请求异常！");
            logger.error("RSA解密异常！失败原因：" + e);
        }
        return result;
    }
    
    /**
     * 电子邮箱重置密码
     * @param users
     * @return
     */
    @GetMapping(value = "email_reset")
    public String onResetForEmailLoad(HttpServletRequest request,ModelMap map) {
        //获取公钥信息
        String path = this.getClass().getResource("/rsakey/publicKey.txt").getFile();
        String publicKey = RSAUtil.readTxt(path);
        map.put("publicKey", publicKey);
        return ftlURL + "ResetPwdForEmail.html";
    }
    
    @Log(title = "使用邮箱重置密码", businessType = BusinessType.OTHER)
    @PostMapping(value = "email_reset")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> UserPasswordResetForEmailAction() {
        InterfaceResult<Map<String, Object>> interfaceResult = new InterfaceResult<>();
        String emailStr = request.getParameter("emailnum");
        String validateCode = request.getParameter("validatecode");
        String newPassword = request.getParameter("newpass");
        String confirmPassword = request.getParameter("confirmpass");
        try {
            // RSA解密
            String privateKey = RSAUtil.readTxt(this.getClass().getResource("/rsakey/privateKey.txt").getFile());
            newPassword = newPassword.replaceAll("%2B","+");
            byte[] decryptPassWord = RSAUtil.decryptByPrivateKey(Base64Util.decode(newPassword), privateKey);
            newPassword = new String(decryptPassWord);
            confirmPassword = confirmPassword.replaceAll("%2B","+");
            byte[] decryptComfirmPass = RSAUtil.decryptByPrivateKey(Base64Util.decode(confirmPassword), privateKey);
            confirmPassword = new String(decryptComfirmPass);
            ServiceResult<Map<String, Object>> serviceResult = usersService.resetpwdForUserEmail(emailStr, 
                    validateCode, newPassword, confirmPassword);
            if(serviceResult.isSuccess()) {
                interfaceResult.setMsg(serviceResult.getMessage());
            }else {
                interfaceResult.setError(serviceResult.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            interfaceResult.setError("数据请求异常！");
            logger.error("RSA解密异常！失败原因：" + e);
        }
        return interfaceResult;
    }
}
